package com.bs.manager05.utils.aop;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.bs.manager05.entity.User;
import com.bs.manager05.utils.RedisUtils;
import com.bs.manager05.utils.TokenUtils;
import com.bs.manager05.utils.auth.Auth;
import com.bs.manager05.utils.exception.NoAuthException;
import com.bs.manager05.utils.exception.NoUserException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author 小姚
 * @pakeageName:com.bs.manager05.utils.aop
 * @ClassName:AuthAspectAop
 * @Descirption:
 * @data 2022/12/19 20:19
 */
//将该类交给spring容器管理
/*@Component
//表明该类是切面类
@Aspect*/
public class AuthAspectAop {

    @Resource
    HttpServletRequest request;

    @Resource
    RedisUtils utils;

    @Around("execution(* com.bs.manager05.controller.*.*(..)) && @annotation(com.bs.manager05.utils.auth.Auth)")
    public Object getAround(ProceedingJoinPoint point) throws Throwable {
        Object o=null;
        //获取请求消息头
        String token = request.getHeader(TokenUtils.TOKEN);
        //判断是否有值,如果不存在值,则表明用户未登录,提示用户登录
        if (StringUtils.isBlank(token)){
            throw new NoUserException("您还未登录，请确认登录之后再访问");
        }
        User user = (User) utils.get(token);
        if(user!=null){
            Signature signature = point.getSignature();
            MethodSignature methodSignature=(MethodSignature) signature;
            Method method = methodSignature.getMethod();
            Auth auth = method.getDeclaredAnnotation(Auth.class);
            if(auth!=null){
                String value = auth.value();
                if(user.getPremission().contains(value)){
                o=point.proceed();
                }else {
                    throw new NoAuthException("您没有访问权限,请联系管理员");
                }
            }
        }else {
            throw new NoUserException("请先登录");
        }

     return o;
    }
}
